// import react, react router
import React, { useContext, useState } from "react";
import { useNavigate, Link } from "react-router-dom";
// import mui
import {
  AppBar,
  Toolbar,
  Button,
  Avatar,
  alpha,
  Typography,
} from "@mui/material";
import { AccountCircle } from "@mui/icons-material";
//import component
import { RowFlexBoxBC, Context, LilySnack } from "../common/Common";
import { isAuthenticated } from "../common/utilities";
import MyCenter from "./MyCenter";
import SearchBar from "../SearchBar/SearchBar";
import { getSearchDataCache } from "../../localCache/searchCache";
/**
 * 这是顶栏组件
 * @param {function} handleLogoutDialog
 * @param {function} handleDark
 * @param {string} userName
 * @param {function} handleRefreshLocalcacheDialog
 * @returns
 */
export default function TopBar({
  handleLogoutDialog,
  handleDark,
  darkMode,
  userName,
  handleRefreshLocalcacheDialog,
}) {
  /* ---------------------------------------------------------
   *                    Snackbar messages
   * ---------------------------------------------------------*/
  const [snackbarMes, setSnackbarMes] = useState({
    text: undefined,
    open: false,
    severity: "warning",
  });
  const navigate = useNavigate(); // 使用 useHistory 钩子
  const isLogin = isAuthenticated();
  const { isVisible, setSearchData } = useContext(Context);
  const NAV_CONSTANCE = [
    { text: "法律法规", url: "/fayucz/legislation" },
    { text: "判决文书", url: "fayucz/judgment" },
    { text: "合同模板", url: "/fayvcz/contract-templates" },
    { text: "法律计算器", url: "/fayucz/lawCounter" },
    { text: "法考题库", url: "/fayucz/lawExam" },
  ];
  const handleNavigate = async (url) => {
    const searchDataCache = await getSearchDataCache();
    if (searchDataCache) {
      // 这会自动检查 searchForm 是否为 null 或 undefined
      navigate(url);
    } else {
      setSnackbarMes({
        text: "当前搜索条件为空，请输入正确的搜索条件",
        open: true,
        severity: "error",
      });
    }
  };

  return (
    <AppBar
      position="fixed"
      sx={{
        boxShadow: 0,
        zIndex: (theme) => theme.zIndex.drawer + 1,
        top: 0,
        left: 0,
        backgroundColor: (theme) => theme.palette.barBackground.main,
        borderColor: alpha("#e5e5e5", 0.1),
        opacity: 0.9, // 添加透明度
      }}
    >
      <Toolbar
        sx={{
          display: "flex",
          flexFlow: "row nowrap",
          justifyContent: "space-between",
          alignItems: "center",
          px: 0,
          height: (theme) => theme.space.barHeight,
        }}
      >
        <RowFlexBoxBC>
          <Avatar
            src="../../assets/images/logo.png"
            alt="Logo"
            sx={{ height: 65, width: 65 }}
            component={Link}
            to={"/"}
          />
          {NAV_CONSTANCE.map((item) => (
            <Typography
              key={item.text}
              variant="body1"
              onClick={() => handleNavigate(item.url)}
              sx={{
                mx: 2,
                color: (theme) => theme.palette.text.main,
                "&:hover": {
                  color: (theme) => theme.palette.hover.secondary,
                  cursor: "pointer", // 添加这行代码
                },
                whiteSpace: "nowrap",
                fontWeight: 800,
              }}
            >
              {item.text}
            </Typography>
          ))}
        </RowFlexBoxBC>

        {isLogin ? (
          <RowFlexBoxBC>
            {isVisible && <SearchBar setSearchData={setSearchData} />}
            <MyCenter
              handleLogoutDialog={handleLogoutDialog}
              darkMode={darkMode}
              handleDark={handleDark}
              userName={userName}
              handleRefreshLocalcacheDialog={handleRefreshLocalcacheDialog}
            />
          </RowFlexBoxBC>
        ) : (
          <RowFlexBoxBC>
            <Button
              variant="contained"
              color="primary"
              startIcon={<AccountCircle />}
              component={Link}
              to={"/login"}
            >
              登录
            </Button>
            <Button
              variant="outlined"
              color="primary"
              startIcon={<AccountCircle />}
              sx={{ ml: "10px" }}
              component={Link}
              to={"/register"}
            >
              注册
            </Button>
          </RowFlexBoxBC>
        )}
        <LilySnack
          duration={snackbarMes.duration}
          open={snackbarMes.open}
          onClose={(event, reason) => {
            if (reason === "clickaway") {
              return;
            }
            setSnackbarMes({ ...snackbarMes, open: false });
          }}
          severity={snackbarMes.severity}
          text={snackbarMes.text}
        />
      </Toolbar>
    </AppBar>
  );
}
